package com.gxw.rxjavatest.utils;

import android.text.TextUtils;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;

public class Strings {

    public static final String SHA1 = "SHA-1";
    public static final String MD5 = "MD5";
    static String UTF8 = "utf-8";
    int BUFFER_SIZE = 8 * 1024;

    public static boolean isNotEmpty(CharSequence str) {
        return !isEmpty(str);
    }

    public static boolean isEmpty(CharSequence str) {
        return str == null || str.length() == 0;
    }

    public static <T> String join(Collection<T> coll, String separator) {
        return join(coll, separator, null);
    }

    public static String join(Object[] arr, String separator) {
        return join(arr, separator, null);
    }

    public static <T> String join(Collection<T> coll, String separator,
                                  String terminator) {
        return join(coll.toArray(new Object[coll.size()]), separator,
                terminator);
    }

    public static String join(Object[] arr, String separator, String terminator) {
        StringBuilder sb = new StringBuilder(arr.length * 2);
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]);
            if (i < arr.length - 1) {
                sb.append(separator);
            } else if (terminator != null && arr.length > 0) {
                sb.append(terminator);
            }
        }
        return sb.toString();
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("failed to encode", e);
        }
    }

    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("failed to decode", e);
        }
    }

    public static String getMD5(String str) {
        try {
            return getHash(str, MD5);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getSHA1(String str) {
        try {
            return getHash(str, SHA1);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getHash(String str, String algorithm)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        byte[] bytes = str.getBytes(UTF8);
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(bytes);
        BigInteger bigInt = new BigInteger(1, digest);
        String hash = bigInt.toString(16);
        while (hash.length() < 32) {
            hash = "0" + hash;
        }
        return hash;
    }

    /**
     * MD5加密
     *
     * @param string
     * @return
     */
    public static String md5(String string) {

        byte[] hash;

        try {

            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));

        } catch (NoSuchAlgorithmException e) {

            throw new RuntimeException("Huh, MD5 should be supported?", e);

        } catch (UnsupportedEncodingException e) {

            throw new RuntimeException("Huh, UTF-8 should be supported?", e);

        }

        StringBuilder hex = new StringBuilder(hash.length * 2);

        for (byte b : hash) {

            if ((b & 0xFF) < 0x10)
                hex.append("0");

            hex.append(Integer.toHexString(b & 0xFF));

        }

        return hex.toString();

    }

    public static final String removeBOM(String data) {
        if (TextUtils.isEmpty(data)) {
            return data;
        }

        if (data.startsWith("\ufeff")) {
            return data.substring(1);
        } else {
            return data;
        }
    }

    public static final String removeTrim(TextView textView) {

        return textView.getText().toString().trim();

    }

    /**
     * 保留i位小数
     * String不能format
     *
     * @param i
     * @param num
     * @return
     */
    public static String formatNum(int i, Double num) {

        String result = String.format("%." + i + "f", num);
        return result;
    }

    public static String formatNum(int i, Float num) {

        String result = String.format("%." + i + "f", num);
        return result;
    }


    /**
     * 设置vin
     *
     * @param vin
     * @return
     * @throws UnsupportedEncodingException
     */
    public static final byte[] regVin(String vin)
            throws UnsupportedEncodingException {
        vin = "0" + vin;
//        if (ID.length() > 14) {
//            ID = ID.substring(ID.length() - 14);
//        }
        return hex2byte(vin);
    }

    /**
     * 十六进制串转化为byte数组
     *
     * @return the array of byte
     */
    public static final byte[] hex2byte(String hex)
            throws IllegalArgumentException {
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }
        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        return b;
    }

    /*
* 16进制数字字符集
*/
    private static String hexString = "0123456789ABCDEF";

    /*
    * 将字符串编码成16进制数字,适用于所有字符（包括中文）
    */
    public static String encode(String str) {
//根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
//将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /**
     * 字节数组转换为十六进制字符串
     *
     * @param b byte[] 需要转换的字节数组
     * @return String 十六进制字符串
     */
    public static final String byte2hex(byte b[]) {
        if (b == null) {
            throw new IllegalArgumentException(
                    "Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * 标识位转义
     *
     * @param bt
     * @return
     */
    public static byte[] antiOfIdentification(byte[] bt) {
        byte[] base = new byte[bt.length * 2];
        int count = 0;
        byte btbase = 0x7d;
        byte btfirst = 0x02;
        byte btend = 0x01;
        base[count] = bt[0];
        count++;
        for (int i = 1; i < bt.length - 1; i++) {
            if (bt[i] == 0x7e) {
                base[count] = btbase;
                count++;
                base[count] = btfirst;
                count++;
            } else if (bt[i] == 0x7d) {
                base[count] = btbase;
                count++;
                base[count] = btend;
                count++;
            } else {
                base[count] = bt[i];
                count++;
            }
        }
        base[count] = bt[bt.length - 1];
        count++;
        byte[] back = new byte[count];
        System.arraycopy(base, 0, back, 0, count);
        return back;
    }

    /**
     * 去除尾部的零
     */
    public static byte[] removeZero(byte[] tcpClient) {
        boolean flag = true;
        while (flag) {
            if (tcpClient != null && tcpClient.length > 0
                    && tcpClient[tcpClient.length - 1] == 0x00) {
                byte[] bt = new byte[tcpClient.length - 1];
                System.arraycopy(tcpClient, 0, bt, 0, tcpClient.length - 1);
                tcpClient = bt;
            } else {
                flag = false;
            }
        }
        return tcpClient;
    }

    /**
     * 判断soc 是否小于0
     *
     * @param s
     * @return
     */
    public static boolean isSmallZero(String s) {
        boolean isSmall = false;
        Double d = Double.valueOf(s);
        if (d < 0) {

            isSmall = true;

        } else {
            isSmall = false;
        }

        return isSmall;

    }

}
